package com.shuziren.controller.system;

import com.shuziren.core.vo.Result;
import com.shuziren.entity.BackgroundUser;
import com.shuziren.entity.vo.BavkgroundUserVo;
import com.shuziren.service.BackgroundUserService;
import com.shuziren.interceptor.JWTTokenUtil;
import com.shuziren.vo.LoginVo;
import com.shuziren.vo.RegisterVo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import shuziren.util.IpUtils;

@RestController
@RequestMapping("/system/user")
public class UserLogin {

    @Autowired
    private BackgroundUserService backgroundUserService;

    /**
     * 用户登录接口
     * @param loginVo 登录信息，包含用户名和密码
     * @return 登录结果，成功返回用户信息，失败返回错误信息
     */
    @PostMapping("/login")
    public Result login(@RequestBody @Validated LoginVo loginVo, HttpServletRequest request ) {
        try {
            String ipAddr = IpUtils.getIpAddr(request);
            String cityInfo = IpUtils.getCityInfo(ipAddr);
            // 调用服务层登录逻辑
            BavkgroundUserVo user = backgroundUserService.login(loginVo);
            if (user != null) {
                BackgroundUser backgroundUse = new BackgroundUser();
                BeanUtils.copyProperties(user, backgroundUse);
                backgroundUse.setIpAttribution(cityInfo);
                backgroundUse.setLastLoginIp(ipAddr);
                int saveloginlog = backgroundUserService.saveloginlog(backgroundUse);
                return Result.success(user);
            } else {
                return Result.fail("用户名或密码错误");
            }
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 用户注册接口
     * @param registerVo 注册信息，包含用户名、密码和邮箱
     * @return 注册结果，成功返回成功信息，失败返回错误信息
     */
    @PostMapping("/register")
    public Result register(@RequestBody RegisterVo registerVo) {
        try {
            // 校验账号、密码是否为空
            registerVo.validate();

            // 创建BackgroundUser对象
            BackgroundUser user = new BackgroundUser();
            user.setUsername(registerVo.getUsername());
            user.setPassword(registerVo.getPassword());
            user.setEmail(registerVo.getEmail());

            // 调用服务层注册逻辑
            backgroundUserService.register(user);
            return Result.success("注册成功");
        } catch (IllegalArgumentException e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 用户退出登录接口
     * @param token 用户的认证令牌
     * @return 退出登录结果，成功返回成功信息
     */
    @GetMapping("/logout")
    public Result logout(@RequestHeader("Authorization") String token,@RequestHeader("username") String username) {
        boolean loginout = backgroundUserService.loginout(token, username);
        return loginout ? Result.success("退出登录成功") : Result.fail("系统错误");
    }

    /**
     * 修改用户密码接口
     * @param id 用户ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 修改结果，成功返回成功信息，失败返回错误信息
     */
    @PostMapping("/changePassword")
    public Result changePassword(
            @RequestParam(value = "id") Integer id,
            @RequestParam(value = "oldPassword") String oldPassword,
            @RequestParam(value = "newPassword") String newPassword) {
        try {
            boolean result = backgroundUserService.changePassword(id, oldPassword, newPassword);
            if (result) {
                return Result.success("密码修改成功");
            } else {
                return Result.fail("密码修改失败");
            }
        } catch (IllegalArgumentException e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 删除用户接口
     * @param id
     * @return
     */
    @PostMapping("/deleteUser")
    public Result deleteUser(@RequestParam("id") Integer id) {
        try {
            backgroundUserService.deleteById(id);
            return Result.success("用户删除成功");
        } catch (Exception e) {
            return Result.fail("用户删除失败：" + e.getMessage());
        }
    }


}